package com.umgsai.wx.backend.test;

import org.apache.commons.lang3.StringUtils;

public class Btest {

    public static void main(String[] args) {
//        System.out.println(convert(".012"));
//        System.out.println(convert("132."));
        System.out.println(convert("132.45"));
    }

    public static float convert(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        int pointCount = 0;
        int numberCount = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '.') {
                pointCount++;
                continue;
            }
            if (s.charAt(i) >= '0' && s.charAt(i) <= '9') {
                numberCount++;
                continue;
            }
            return 0;
        }
        if (pointCount > 1) {
            // 多个点
            return 0;
        }
        if (numberCount == 0) {
            // 无数字
            return 0;
        }
        String[] split = StringUtils.split(s, ".");
        if (split.length == 1) {
            String s1 = split[0];
            // .011 同0.011
            if (s.charAt(0) == '.') {
                return convert1(s1);
            } else {
                return convert2(s1);
            }
        }
        String s1 = split[0];
        String s2 = split[1];

        float result1 = convert2(s1);
        float result2 = convert1(s2);

        return result2 + result1;
    }

    private static float convert1(String s1) {
        float result = 0;
        for (int i = 0; i < s1.length(); i++) {
            result += (float) ((float) s1.charAt(i) - '0') / (float) (Math.pow(10, i + 1));
        }
        return result;
    }

    private static float convert2(String s1) {
        float result = 0;
        int count = 0;
        for (int i = s1.length() - 1; i >= 0; i--) {
            result += (float) ((float) s1.charAt(i) - '0') * (float) (Math.pow(10, count++));
        }
        return result;
    }
}
